﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;
using IUploading;

namespace DataTransferClient
{
    public class TransferResponseReceiveFilter : FixedHeaderReceiveFilter<TransferResponsePackageInfo>
    {
        // 回复协议定义规则
        // +-------+---+-------------------------------+
        // |response | l  |                               |
        // | name    | e |    response body      |
        // |  (2)        | n |                               |
        // |              |(4)|                               |
        // +-------+---+-------------------------------+
        // 其中前2位字节存储请求命令的名称，
        // 第3-6位存储请命令主体的总子节数(字节数组的长度)
        public TransferResponseReceiveFilter()
        : base(6)
        {

        }

        protected override int GetBodyLengthFromHeader(IBufferStream bufferStream, int length)
        {
            ArraySegment<byte> buffers = bufferStream.Buffers[0];
            byte[] array = buffers.Array;         
            var headerData = new byte[4];
            Array.Copy(array, 2, headerData, 0, 4);
            int len = BitConverter.ToInt32(headerData, 0);
            return len;
        }

        public override TransferResponsePackageInfo ResolvePackage(IBufferStream bufferStream)
        {
            var headerData = new byte[2];
            byte[] header = bufferStream.Buffers[0].Array;
            Array.Copy(header, 0, headerData, 0, 2);
            TransferResult state = (TransferResult)BitConverter.ToUInt16(headerData, 0);
            ArraySegment<byte> array = bufferStream.Buffers[1];
            byte[] bodyBuffer = array.Array;
            byte[] reallyBody = bodyBuffer.Skip(array.Offset).Take(array.Count).ToArray();
            return new TransferResponsePackageInfo(state, reallyBody);
        }
    }
}
